import {
	formatDate
} from "./dateFormat.js";

/**  
 * 节流  
 */
export function throttle(fn, wait = 500, isImmediate = false) {
	let flag = true;
	if (isImmediate) {
		return function() {
			if (flag) {
				fn.apply(this, arguments);
				flag = false;
				setTimeout(() => {
					flag = true
				}, wait)
			}
		}
	}
	return function() {
		if (flag == true) {
			flag = false
			setTimeout(() => {
				fn.apply(this, arguments)
				flag = true
			}, wait)
		}
	}
}

//防抖  
export function debounce(fn, wait = 500, isImmediate = false) {
	let timerId = null;
	let flag = true;
	if (isImmediate) {
		return function() {
			clearTimeout(timerId);
			if (flag) {
				fn.apply(this, arguments);
				flag = false
			}
			timerId = setTimeout(() => {
				flag = true
			}, wait)
		}
	}
	return function() {
		clearTimeout(timerId);
		timerId = setTimeout(() => {
			fn.apply(this, arguments)
		}, wait)
	}
}
/**
 * 缓存列表设置
 */
export function setStorageList(search_key, search_value) {
	const initData = JSON.stringify([])
	const listStr = uni.getStorageSync(search_key) || initData
	const list = JSON.parse(listStr)
	let newList = [...list]
	if (list.includes(search_value)) {
		newList = list.filter(str => str !== search_value)
		newList.unshift(search_value)
	} else {
		newList.unshift(search_value)
	}
	uni.setStorageSync(search_key, JSON.stringify(newList))
	return newList;
}

export function clearStorageAll(search_key) {
	const initData = JSON.stringify([])
	uni.setStorageSync(search_key, initData)
}

export function clearStorage(search_key, search_value) {
	const initData = JSON.stringify([])
	const listStr = uni.getStorageSync(search_key) || initData
	const list = JSON.parse(listStr)
	let newList = [...list]
	if (list.includes(search_value)) {
		newList = list.filter(str => str !== search_value)
	}
	uni.setStorageSync(search_key, JSON.stringify(newList))
	return newList;
}
export const dateFormat = (timestamp, format = "yyyy-MM-dd hh:mm") => {
	return formatDate(timestamp * 1000, format)
}